package com.gxa.Interceptor;

import com.alibaba.fastjson.JSONObject;
import com.gxa.common.R;
import com.gxa.utils.JwtResult;
import com.gxa.utils.JwtUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String token = httpServletRequest.getHeader("token");
        R r = new R();
        if (token!=null){
            JwtResult jwtResult = JwtUtils.validateJwt(token);
            if (jwtResult.isSuccess()){
                return  true;
            }else if (JwtUtils.JWT_ERRCODE_EXPIRE==jwtResult.getErrCode()) {
               r.setCode(1005);
               r.setMsg("Token过期");
            }else {
                r.setData("验证不通过");
                r.setCode(1006);
            }
        }else {
            r.setCode(500);
            r.setMsg("还没登录");
        }
        httpServletResponse.setCharacterEncoding("utf-8");
        Object o1 = JSONObject.toJSON(r);
        httpServletResponse.getWriter().write(String.valueOf(o1));
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
